package com.shenmazong.delayqueue.demo01;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * @program: server-java-demo
 * @description: DelayQueueDemo01
 * @author: 亮子说编程
 * @create: 2020-11-02 13:48
 **/
public class DelayQueueDemo01 {

    public static void main(String[] args) throws InterruptedException {

        OrderRecord order1 = new OrderRecord("OrderRecord1", 5, TimeUnit.SECONDS);
        OrderRecord order2 = new OrderRecord("OrderRecord2", 10, TimeUnit.SECONDS);
        OrderRecord order3 = new OrderRecord("OrderRecord3", 15, TimeUnit.SECONDS);

        DelayQueue<OrderRecord> delayQueue = new DelayQueue<>();
        delayQueue.put(order1);
        delayQueue.put(order2);
        delayQueue.put(order3);

        System.out.println("订单延迟队列开始时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        while (delayQueue.size() != 0) {
            /**
             * 取队列头部元素是否过期
             */
            OrderRecord task = delayQueue.poll();
            if (task != null) {
                System.out.format("订单:{%s}被取消, 取消时间:{%s}\n", task.name, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            Thread.sleep(1000);
        }
    }

}
